<template>
  <div class="department-station-selector">
    <!-- 触发按钮 -->
    <el-button 
      @click="showDialog" 
      type="primary" 
      :size="size"
      class="trigger-button"
      plain
    >
      <i class="el-icon-location"></i>
      {{ selectedName || placeholder }}
    </el-button>

    <!-- 选择器对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="选择部门岗位"
      width="600px"
      :close-on-click-modal="false"
      :modal="false"
      class="selector-dialog"
      append-to-body
    >
      <div class="dialog-content">
        <el-tree
          ref="treeRef"
          :data="treeData"
          node-key="id"
          :props="defaultProps"
          :highlight-current="true"
          :expand-on-click-node="true"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span class="node-icon">
              <i :class="data.type === 'department' ? 'el-icon-folder' : 'el-icon-user'"></i>
            </span>
            <span class="node-label">{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="!currentSelection"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DepartmentStationSelector',
  props: {
    value: [String, Number], // v-model 绑定值
    placeholder: {
      type: String,
      default: '请选择部门/岗位'
    },
    size: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      dialogVisible: false,
      treeData: [],
      currentSelection: null,
      selectedName: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    // 获取部门数据
    async fetchDepartmentData() {
      try {
        const response = await this.$get('/employee/department')
        if (response.result === 200 && response.data) {
          console.log('API返回数据:', response.data)
          this.treeData = this.processTreeData(response.data)
          console.log('处理后的树形数据:', this.treeData)
        } else {
          this.$message.error('获取部门数据失败')
        }
      } catch (error) {
        console.error('获取部门数据错误:', error)
        this.$message.error('获取部门数据失败')
      }
    },
    // 处理树形数据
    processTreeData(data) {
      if (!Array.isArray(data)) return []
      
      return data.map(item => {
        const node = {
          id: item.id,
          name: item.name,
          type: 'department',
          children: []
        }
        
        // 处理子部门
        if (Array.isArray(item.children) && item.children.length > 0) {
          node.children = this.processTreeData(item.children)
        }
        
        // 处理岗位
        if (Array.isArray(item.station) && item.station.length > 0) {
          const stationNodes = item.station.map(station => ({
            id: station.id,
            name: station.name,
            type: 'station'
          }))
          node.children = node.children.concat(stationNodes)
        }
        
        return node
      })
    },
    // 节点点击处理
    handleNodeClick(data) {
      console.log('点击节点:', data) // 调试日志
      this.currentSelection = data
      
    },
    // 确认选择
    handleConfirm() {
      if (!this.currentSelection) {
        this.$message({
          type: 'warning',
          message: '请选择具体的岗位'
        })
        return
      }
      
      if (this.currentSelection.type !== 'station') {
        this.$message({
          type: 'warning',
          message: '请选择具体的岗位，不能选择部门'
        })
        return
      }

      // 获取上级部门信息
      const parentDepartment = this.findParentDepartment(this.treeData, this.currentSelection.id)
      
      // 构建选择结果对象
      const selectionResult = {
        station: {
          id: this.currentSelection.id,
          name: this.currentSelection.name
        },
        department: parentDepartment ? {
          id: parentDepartment.id,
          name: parentDepartment.name
        } : null
      }

      this.selectedName = this.currentSelection.name
      this.$emit('input', this.currentSelection.id)
      this.$emit('change', selectionResult)
      this.dialogVisible = false
    },
    // 查找父部门
    findParentDepartment(treeData, stationId) {
      for (const node of treeData) {
        const result = this.findParentDepartmentRecursive(node, stationId)
        if (result) return result
      }
      return null
    },
    // 递归查找父部门
    findParentDepartmentRecursive(node, stationId) {
      // 如果当前节点是部门，检查其子节点
      if (node.type === 'department') {
        // 检查岗位节点
        const stationNode = node.children.find(child => 
          child.type === 'station' && child.id === stationId
        )
        if (stationNode) {
          return node
        }
        
        // 递归检查子部门
        for (const child of node.children) {
          if (child.type === 'department') {
            const result = this.findParentDepartmentRecursive(child, stationId)
            if (result) return result
          }
        }
      }
      return null
    },
    // 取消选择
    handleCancel() {
      this.dialogVisible = false
      this.currentSelection = null
    },
    // 显示对话框
    showDialog() {
      this.dialogVisible = true
    },
    handleStationChange(station) {
      console.log('选中的岗位信息:', station)
      this.formData.stationId = station.id
      this.formData.station = station.name
      this.$message.success(`已选择岗位: ${station.name}`)
    }
  },
  mounted() {
    this.fetchDepartmentData()
  }
}
</script>

<style scoped>
.department-station-selector {
  display: inline-block;
  width: 100%;
}

.trigger-button {
  width: 100% !important;
  text-align: left;
  padding-left: 15px;
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
  
.trigger-button i {
  margin-right: 8px;
}

.dialog-content {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
  padding: 8px 0;
}

.node-icon {
  margin-right: 8px;
  color: #409EFF;
}

.node-icon i {
  font-size: 16px;
}

.node-label {
  color: #606266;
}

/* 树节点hover效果 */
.el-tree-node__content:hover {
  background-color: #F5F7FA;
}

/* 选中节点样式 */
.el-tree-node.is-current > .el-tree-node__content {
  background-color: #ecf5ff;
  color: #409EFF;
}

/* 树节点hover效果 */
.el-tree-node__content:hover {
  background-color: #F5F7FA;
}

/* 对话框样式 */
.selector-dialog {
  border-radius: 4px;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

/* 滚动条样式 */
.dialog-content::-webkit-scrollbar {
  width: 6px;
}

.dialog-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.dialog-content::-webkit-scrollbar-track {
  background: #f5f7fa;
}

/* 动画效果 */
.el-dialog__body {
  padding: 20px !important;
}

.el-tree-node__content {
  transition: background-color 0.3s ease;
}

.el-button {
  transition: all 0.3s ease;
}
</style> 